//导入Ajax
import {
    ajax,
    isObject
} from "./ajax.js"

//获取本地的购物车数据
var cararr = true;
var bookcardata = {};
localStorage.getItem("thingcarhistory")
var thistory = localStorage.getItem("thingcarhistory")
var carharr = JSON.parse(thistory)
var str = "";
if(carharr){
    if(carharr[0]){
        for(var i = 0;i<carharr.length;i++){
            var j = i;
            ajax({
                url: "./php/search.php",
                dataType: "json",
                data: {ways:"detail",id:carharr[i]['id']},
                type: "get",
                cache: false,
                //调用成功执行函数
                success: function (data) {
                    str +=`
                    <div class="goods ">
                    <div>
                        <input type="checkbox" class="checkone">
                        <a href="./detail.html?bname=${escape(data[0]['id'])}">
                            <img src=${data[0]["url"]} alt="">
                        </a>
                        <a href="./detail.html?bname=${escape(data[0]['id'])}" class="bookname">
                            <span>
                            ${data[0]["goodsname"]}
                            </span>
                        </a>
                    </div>
                    <div>${data[0]["price2"]}</div>
                    <div>
                    ${data[0]["price2"].split("￥")[1]*10*carharr[j]['num']}
                    </div>
                    <div>
                    ${data[0]["shop"]}
                    </div>
                     <div>
                         <button></button>
                         <input type="text"  value="${carharr[j]['num']}">
                         <button></button>
                     </div>
                     <div>
                        <b>删除</b>
                     </div>
                </div>
                    `
                    if(j==carharr.length-1){
                        $(".carcont").html(str)
                    }
                },
                error: function (x) {
                    alert(x)
                }
            })
        }
    }
}

    
if(carharr){
    if(carharr[0]){
        cararr = false;
    }else{
        cararr = true;
    }
}

// 渲染页面
if(cararr){
    $(".content .havegoods")[0].style.display = "none"
    $(".continue span")[0].style.display = "none"
    $(".content .empty")[0].style.display = "block"
}else{
    $(".content .empty")[0].style.display = "none"
// 调用ajax，获取购物车的内容****************************

// 调用ajax，获取购物车的内容****************************

}
result()
//添加事件监听
$(".havegoods").on("click",function(e){
    //事件对象
    var e = e || window.event;
    //事件目标
    var target = e.target || e.srcElement;
    //当点击全选********
    if(target.className=="checkall1"){
        //判断是否全选
        if(target.checked){
            for(var i =0;i<$(".goods input[type='checkbox']").length;i++){
                $(".goods input[type='checkbox']")[i].checked = true
            }
        }else{
            for(var i =0;i<$(".goods input[type='checkbox']").length;i++){
                $(".goods input[type='checkbox']")[i].checked = false
            }
        }
        result()
    }
    //当点击全选********

    //增加或减少数量************
    if(target.nodeName=="BUTTON"){
        //判断是加还是减
        if(target===target.parentNode.children[0]){
            //当为减时
            if(target.parentNode.children[1].value<=1){
                target.parentNode.children[1].value = 1
                return
            }
            target.parentNode.children[1].value--
        }else{
            target.parentNode.children[1].value++
        }
        var price = target.parentNode.parentNode.children[1].innerHTML.split("￥")[1]
        target.parentNode.parentNode.children[2].innerHTML = parseInt(price*target.parentNode.children[1].value*10)
        result()
    }
    //增加或减少数量************

    //单项商品是否选择
    if(target.className=="checkone"){
        checkone()
    }
    function checkone(){
        var check =true;
        for(var i =0;i<$(".goods input[type='checkbox']").length;i++){
            if($(".goods input[type='checkbox']")[i].checked == true){

            }else{

                check =false;
            }
        }
        $(".checkall1")[0].checked = check
        result()
    }
    //单项商品是否选择

    //删除单项商品***
    if(target.innerHTML=="删除"){
        var na = unescape(target.parentNode.parentNode.children[0].children[1].getAttribute("href")).split("?")[1].split("=")[1]
        var buu=carharr.indexOf(carharr.find(item=>{
            if(item.id == na){
                return item
            }
        }))
        carharr.splice(buu, 1);
        var ad = JSON.stringify(carharr)
        localStorage.setItem("thingcarhistory" , ad)
        target.parentNode.parentNode.remove()
        checkone()
    }
    //删除单项商品***


    //删除所选商品***
    if(target.className=="sum-left"){
        for(var i =0;i<$(".goods input[type='checkbox']").length;i++){
            if($(".goods input[type='checkbox']")[i].checked == true){
                var na = unescape($(".goods input[type='checkbox']")[i].parentNode.parentNode.children[0].children[1].getAttribute("href")).split("?")[1].split("=")[1]
                var buu=carharr.indexOf(carharr.find(item=>{
                    if(item.id == na){
                        return item
                    }
                }))
                carharr.splice(buu, 1);
                $(".goods input[type='checkbox']")[i].parentNode.parentNode.remove()
                i--
            }else{

            }
        }
        var ad = JSON.stringify(carharr)
        localStorage.setItem("thingcarhistory" , ad)
        result()
    }
    //删除所选商品***

})
    //计算总价*******************
    function result(){
        //总价
        var total = 0
        var num1 = 0
        for(var j=0;j<$(".goods").length;j++){
            if($(".goods")[j].children[0].children[0].checked){
                //当前商品的单价
                var price1= Number($(".goods")[j].children[1].innerHTML.split("￥")[1])
                //当前商品的数量
                var num = $(".goods")[j].children[4].children[1].value
                total += (price1*num)
                num1++
            }
        }
        total = total.toFixed(2)
        $(".sum-right p")[0].children[0].innerHTML = "￥"+total
        $(".sum-right")[0].children[0].children[0].innerHTML = num1
        $(".total p span").html("￥"+total)
    }
    //计算总价*******************

    //确认付款
    $('.sure').on('click',()=>{
        if(parseFloat($(".total p span").html().split("￥")[1])>0){
            $.post('https://m.28sjw.com/order/getQR.php', {
                _s:"hoa",
                _f:1,
                _t:2
            }, function (data) {
                var str=`    
                <div class="bblack">
                <div class="payfor">
                    <img src="${data.qr_code}">
                    <br>
                    <span>
                        欢迎选购,请扫码支付
                    </span>
                    <img src="./imgs/a4c2dec6211ae120636363808a8c1227.jpeg" alt="" class="nopay">
                    <br>
                    <span class="settime">30</span>
                </div>
                </div>`
                $('body').append(str)
                $('.nopay').on('click',()=>{
                    $('.bblack')[0].style.display = 'none';
                })
                var set1 = setInterval(()=>{
                    var a=$('.settime').html()
                    var a = parseInt(a)
                    a--
                    $('.settime').html(a)
                    if(a==0){
                        clearInterval(set1)
                        $.post('https://m.28sjw.com/order/orderPayStatusCheck.php', {
                            _oid:data.order_id,
                        }, function (data) {
                            console.log(data.data.order_status)
                            if(data.data.order_status=="0"){
                                alert("支付失败,请稍后重新再试。")
                                location.reload();
                            }else{
                                alert("支付成功,我们很快就发货。")
                                for(var i =0;i<$(".goods input[type='checkbox']").length;i++){
                                    if($(".goods input[type='checkbox']")[i].checked == true){
                                        var na = unescape($(".goods input[type='checkbox']")[i].parentNode.parentNode.children[0].children[1].getAttribute("href")).split("?")[1].split("=")[1]
                                        var buu=carharr.indexOf(carharr.find(item=>{
                                            if(item.id == na){
                                                return item
                                            }
                                        }))
                                        carharr.splice(buu, 1);
                                        $(".goods input[type='checkbox']")[i].parentNode.parentNode.remove()
                                        i--
                                    }else{
                        
                                    }
                                }
                                var ad = JSON.stringify(carharr)
                                localStorage.setItem("thingcarhistory" , ad)
                                location.reload();
                            }
                        });
    
                    }
            },1000)
            });
        }
    })
